﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.Businesses
{
    public static class List
    {
        public static Adams.Web.Models.Businesses.List.PageLoad PageLoad(string type, string category)
        {
            var data = new Adams.Web.Models.Businesses.List.PageLoad() { 
                Businesses = new Shared.Entities.Businesses.BusinessCollection()
            };

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT P.BusinessID,P.CategoryID,P.StatusID,P.Name,P.Street,P.Street2,P.City,P.State,P.Zip,P.Phone,P.Description,P.CreatedOn,P.ExpiresOn,C.Name As CategoryName,T.TypeID AS TypeID, T.Name AS TypeName
FROM Businesses.Businesses P 
INNER JOIN Businesses.Categories C ON P.CategoryID = C.CategoryID 
INNER JOIN Businesses.Types T ON C.TypeID = T.TypeID 
WHERE T.Name = @Type" + (string.IsNullOrEmpty(category) ? "" : @" AND C.Name = @Category") + @"
AND P.StatusID = 2 AND DATEDIFF(d, GETDATE(), P.ExpiresOn) >= 0
ORDER BY ExpiresOn DESC
", CommandType.Text,
    DB.CreateParameter("@Type", type),
    DB.CreateParameter("@Category", category)))
            {
                while (dr.Read())
                {
                    var Business = DB.InitFromReader<Shared.Entities.Businesses.Business>(dr, new ColMap { NameInDb = "BusinessID", NameInObject = "ID" });
                    Business.Status = (Shared.Entities.Businesses.Status)dr["StatusID"].DbInt();
                    data.Businesses.Add(Business);
                }
            }

            return data;
        }
    }
}